import {EventEmitter} from '../../base/events';
import uuidv4 from 'uuid/v4'
import { Stud, AllSerialUsages } from '../Stud';
import { WireFigure } from '../../graph/WireFigure';
import { Bus } from './Bus';
import { PartHost } from '../parts/PartBase';
import { Usage } from '../StudUsage';

export class Wire extends EventEmitter{

    public uuid: string = uuidv4()

    public bus?: Bus

    public figure?: WireFigure

    public destroyed = false

    constructor(public from:Stud, public to:Stud) {
        super()

        if( (from.part instanceof PartHost) && !(to.part instanceof PartHost) ) {
            this.autoSetUsage(from, to)
        }
        else if( !(from.part instanceof PartHost) && (to.part instanceof PartHost) ) {
            this.autoSetUsage(to, from)
        }
    }

    public another(stud: Stud) {
        if(this.from==stud) {
            return this.to
        }
        else if(this.to==stud) {
            return this.from
        }
        else {
            return undefined
        }
    }

    public destroy() {
        this.from.wires.removeFirst(this)
        this.to.wires.removeFirst(this)
        delete (this as any).to
        delete (this as any).from
        delete this.figure
        this.destroyed = true
    }

    public serialize() {
        return {
            uuid: this.uuid ,
            from: {
                part: this.from.part.uuid ,
                stud: this.from.info.name
            } ,
            to: {
                part: this.to.part.uuid ,
                stud: this.to.info.name
            }
        }
    }

    public autoSetUsage(hostStud:Stud, slaveStud: Stud){
        if(!slaveStud.usage || slaveStud.usage==Usage.none){
            return true
        }
        if(hostStud.usage==slaveStud.usage) {
            return true
        }
        if(hostStud.usage!=Usage.none)
            return false

        

        return true
    }
}